package com.atguigu.day05;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

public class Flink05_CountWindow_SlidingWnidow {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);


        //3.将数据转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //4.将相同id的数据聚合到一块
//        KeyedStream<WaterSensor, String> keyBy = map.keyBy(WaterSensor::getId);
        KeyedStream<WaterSensor, String> keyBy = map.keyBy(r -> r.getId());

        //TODO 5.开启一个基于元素个数的滑动窗口，窗口大小为5，滑动为步长2
        WindowedStream<WaterSensor, String, GlobalWindow> window = keyBy.countWindow(5,2);
        //计算范围是针对每个分组的每个窗口
        SingleOutputStreamOperator<WaterSensor> sum = window.sum("vc");

        sum.print();

        env.execute();
    }
}
